#!/usr/bin/python3
# -*- coding: utf-8; tab-width: 4; indent-tabs-mode: t -*-

import os
import logging
import subprocess
from mc_util import McUtil


class Advertiser:

    @staticmethod
    def get_properties():
        return {
            "need-temp-directory": True,
            "storage-dependencies": ["file", "postgresql"],
        }

    def __init__(self, param):
        self._tmpDir = param["temp-directory"]
        self._virtRootDir = os.path.join(self._tmpDir, "vroot")
        self._listenIp = param["listen-ip"]

        self._port = None
        self._proc = None
        self._mirrorSiteDict = dict()
        self._advertisedMirrorSiteIdList = []
        try:
            os.makedirs(self._virtRootDir, exist_ok=True)
            self._port = McUtil.getFreeSocketPort("tcp")
            self._proc = subprocess.Popen([
                "java",
                "-jar",
                GITBUCKET_JAR,
                "--host=%s" % (self._listenIp),
                "--port=%d" % (self._port),
                "--gitbucket.home=" + self._virtRootDir,
            ], cwd=self._tmpDir)
            McUtil.waitSocketPortForProc("tcp", self._listenIp, self._port, self._proc)
            logging.info("Advertiser (gitbucket) started, listening on port %d." % (self._port))
        except Exception:
            self.dispose()
            raise

    def dispose(self):
        if self._proc is not None:
            self._proc.terminate()
            self._proc.wait()
            self._proc = None
        if self._port is not None:
            self._port = None
        McUtil.forceDelete(self._virtRootDir)

    def add_mirror_site(self, mirror_site_id, mirror_site_properties):
        assert mirror_site_id not in self._mirrorSiteDict
        self._mirrorSiteDict[mirror_site_id] = mirror_site_properties

    def advertise_mirror_site(self, mirror_site_id):
        assert mirror_site_id in self._mirrorSiteDict and mirror_site_id not in self._advertisedMirrorSiteIdList
        self._advertisedMirrorSiteIdList.append(mirror_site_id)

        realPath = self._mirrorSiteDict[mirror_site_id]["storage-param"]["file"]["data-directory"]
        os.symlink(realPath, os.path.join(self._virtRootDir, mirror_site_id))

    def remove_mirror_site(self, mirror_site_id):
        assert mirror_site_id in self._mirrorSiteDict
        if mirror_site_id in self._advertisedMirrorSiteIdList:
            self._advertisedMirrorSiteIdList.remove(mirror_site_id)
        del self._mirrorSiteDict[mirror_site_id]

        os.unlink(os.path.join(self._virtRootDir, mirror_site_id))

    def get_access_info(self, mirror_site_id):
        assert mirror_site_id in self._advertisedMirrorSiteIdList
        return {
            "url": "http://{IP}:%d/%s" % (self._port, mirror_site_id),
            "description": "",
        }





# https://stackoverflow.com/questions/11119270/how-to-import-github-issues-and-wikis-to-bitbucket
